﻿import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../core/controllers/ring_controller.dart';
import '../../../services/ring_service.dart';

/// 戒指数据页面
/// 显示戒指连接状态、设备扫描和各类健康数据
class RingView extends GetView<RingController> {
  const RingView({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('AzRing 戒指'),
        backgroundColor: Get.theme.colorScheme.primaryContainer,
        foregroundColor: Get.theme.colorScheme.onPrimaryContainer,
        actions: [
          // 刷新按钮
          Obx(() => IconButton(
            onPressed: controller.isLoading ? null : controller.refreshDeviceStatus,
            icon: controller.isLoading 
              ? const SizedBox(
                  width: 20,
                  height: 20,
                  child: CircularProgressIndicator(strokeWidth: 2),
                )
              : const Icon(Icons.refresh),
            tooltip: '刷新',
          )),
        ],
      ),
      body: Column(
        children: [
          // 连接状态卡片
          _buildConnectionStatusCard(),
          
          // 主要内容区域
          Expanded(
            child: Obx(() {
              if (!controller.isConnected) {
                return _buildDeviceDiscoverySection();
              } else {
                return _buildDataDisplaySection();
              }
            }),
          ),
        ],
      ),
    );
  }

  /// 构建连接状态卡片
  Widget _buildConnectionStatusCard() {
    return Obx(() => Container(
      margin: const EdgeInsets.all(16),
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: _getStatusColor().withOpacity(0.1),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(
          color: _getStatusColor().withOpacity(0.3),
          width: 1,
        ),
      ),
      child: Row(
        children: [
          Icon(
            _getStatusIcon(),
            color: _getStatusColor(),
            size: 24,
          ),
          const SizedBox(width: 12),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  controller.statusMessage,
                  style: Get.textTheme.titleMedium?.copyWith(
                    color: _getStatusColor(),
                    fontWeight: FontWeight.bold,
                  ),
                ),
                if (controller.connectedDevice != null) ...[
                  const SizedBox(height: 4),
                  Text(
                    controller.connectedDevice!.name,
                    style: Get.textTheme.bodyMedium?.copyWith(
                      color: Get.theme.colorScheme.onSurfaceVariant,
                    ),
                  ),
                ],
              ],
            ),
          ),
          if (controller.isConnected) ...[
            // 电池电量显示
            _buildBatteryIndicator(),
            const SizedBox(width: 8),
            // 断开连接按钮
            IconButton(
              onPressed: controller.isLoading ? null : controller.disconnectDevice,
              icon: const Icon(Icons.link_off),
              tooltip: '断开连接',
            ),
          ],
        ],
      ),
    ));
  }

  /// 构建设备发现区域
  Widget _buildDeviceDiscoverySection() {
    return Padding(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          // 扫描控制按钮
          Row(
            children: [
              Expanded(
                child: Obx(() => ElevatedButton.icon(
                  onPressed: controller.isScanning 
                    ? controller.stopScan 
                    : controller.scanDevices,
                  icon: Icon(controller.isScanning 
                    ? Icons.stop 
                    : Icons.search),
                  label: Text(controller.isScanning 
                    ? '停止扫描' 
                    : '扫描设备'),
                  style: ElevatedButton.styleFrom(
                    padding: const EdgeInsets.symmetric(vertical: 12),
                  ),
                )),
              ),
            ],
          ),
          
          const SizedBox(height: 16),
          
          // 设备列表
          Expanded(
            child: Obx(() {
              if (controller.isScanning && controller.scannedDevices.isEmpty) {
                return const Center(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      CircularProgressIndicator(),
                      SizedBox(height: 16),
                      Text('正在扫描设备...'),
                    ],
                  ),
                );
              }
              
              if (controller.scannedDevices.isEmpty) {
                return Center(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Icon(
                        Icons.bluetooth_searching,
                        size: 64,
                        color: Get.theme.colorScheme.outline,
                      ),
                      const SizedBox(height: 16),
                      Text(
                        '未发现设备',
                        style: Get.textTheme.titleMedium?.copyWith(
                          color: Get.theme.colorScheme.outline,
                        ),
                      ),
                      const SizedBox(height: 8),
                      Text(
                        '请确保戒指已开启并点击扫描',
                        style: Get.textTheme.bodyMedium?.copyWith(
                          color: Get.theme.colorScheme.outline,
                        ),
                      ),
                    ],
                  ),
                );
              }
              
              return ListView.builder(
                itemCount: controller.scannedDevices.length,
                itemBuilder: (context, index) {
                  final device = controller.scannedDevices[index];
                  return _buildDeviceCard(device);
                },
              );
            }),
          ),
        ],
      ),
    );
  }

  /// 构建设备卡片
  Widget _buildDeviceCard(RingDevice device) {
    return Card(
      margin: const EdgeInsets.only(bottom: 8),
      child: ListTile(
        leading: Icon(
          Icons.bluetooth,
          color: Get.theme.colorScheme.primary,
        ),
        title: Text(
          device.name,
          style: Get.textTheme.titleMedium,
        ),
        subtitle: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('地址: ${device.address}'),
            Text('信号强度: ${device.rssi} dBm'),
          ],
        ),
        trailing: ElevatedButton(
          onPressed: () => controller.connectDevice(device),
          child: const Text('连接'),
        ),
        isThreeLine: true,
      ),
    );
  }

  /// 构建数据显示区域
  Widget _buildDataDisplaySection() {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          // 快速操作按钮
          _buildQuickActionsRow(),
          
          const SizedBox(height: 16),
          
          // 数据卡片网格
          _buildDataCardsGrid(),
        ],
      ),
    );
  }

  /// 构建快速操作按钮行
  Widget _buildQuickActionsRow() {
    return Row(
      children: [
        Expanded(
          child: ElevatedButton.icon(
            onPressed: controller.isLoading ? null : controller.fetchAllData,
            icon: const Icon(Icons.sync),
            label: const Text('同步数据'),
          ),
        ),
        const SizedBox(width: 8),
        Expanded(
          child: ElevatedButton.icon(
            onPressed: controller.isLoading ? null : controller.syncTime,
            icon: const Icon(Icons.access_time),
            label: const Text('同步时间'),
          ),
        ),
      ],
    );
  }

  /// 构建数据卡片网格
  Widget _buildDataCardsGrid() {
    return Obx(() => Column(
      children: [
        // 第一行：步数和心率
        Row(
          children: [
            Expanded(child: _buildStepsCard()),
            const SizedBox(width: 8),
            Expanded(child: _buildHeartRateCard()),
          ],
        ),
        
        const SizedBox(height: 8),
        
        // 第二行：睡眠
        _buildSleepCard(),
        
        const SizedBox(height: 8),
        
        // 第三行：心率测量控制
        _buildHeartRateMeasureCard(),
      ],
    ));
  }

  /// 构建步数卡片
  Widget _buildStepsCard() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Icon(
                  Icons.directions_walk,
                  color: Get.theme.colorScheme.primary,
                ),
                const SizedBox(width: 8),
                Text(
                  '步数',
                  style: Get.textTheme.titleMedium,
                ),
              ],
            ),
            const SizedBox(height: 12),
            Obx(() {
              final stepsData = controller.stepsData;
              if (stepsData == null) {
                return const Text('暂无数据');
              }
              
              return Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    controller.getFormattedSteps(),
                    style: Get.textTheme.headlineMedium?.copyWith(
                      color: Get.theme.colorScheme.primary,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  const SizedBox(height: 4),
                  Text('距离: ${controller.getFormattedDistance()}'),
                  Text('卡路里: ${controller.getFormattedCalories()}'),
                ],
              );
            }),
          ],
        ),
      ),
    );
  }

  /// 构建心率卡片
  Widget _buildHeartRateCard() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Icon(
                  Icons.favorite,
                  color: Colors.red,
                ),
                const SizedBox(width: 8),
                Text(
                  '心率',
                  style: Get.textTheme.titleMedium,
                ),
              ],
            ),
            const SizedBox(height: 12),
            Obx(() {
              final heartRate = controller.heartRate;
              if (heartRate == 0) {
                return const Text('暂无数据');
              }
              
              return Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    '$heartRate',
                    style: Get.textTheme.headlineMedium?.copyWith(
                      color: Colors.red,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  const SizedBox(height: 4),
                  Text('bpm'),
                  Text(
                    controller.getHeartRateStatus(),
                    style: Get.textTheme.bodySmall,
                  ),
                ],
              );
            }),
          ],
        ),
      ),
    );
  }

  /// 构建睡眠卡片
  Widget _buildSleepCard() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Icon(
                  Icons.bedtime,
                  color: Get.theme.colorScheme.secondary,
                ),
                const SizedBox(width: 8),
                Text(
                  '睡眠',
                  style: Get.textTheme.titleMedium,
                ),
              ],
            ),
            const SizedBox(height: 12),
            Obx(() {
              final sleepData = controller.sleepData;
              if (sleepData == null) {
                return const Text('暂无数据');
              }
              
              return Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    controller.getFormattedSleepTime(),
                    style: Get.textTheme.headlineSmall?.copyWith(
                      color: Get.theme.colorScheme.secondary,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  const SizedBox(height: 8),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text('深睡: ${sleepData.deepSleepTime}min'),
                      Text('浅睡: ${sleepData.lightSleepTime}min'),
                    ],
                  ),
                  const SizedBox(height: 4),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text('REM: ${sleepData.remSleepTime}min'),
                      Text('醒来: ${sleepData.awakeTimes}次'),
                    ],
                  ),
                ],
              );
            }),
          ],
        ),
      ),
    );
  }

  /// 构建心率测量控制卡片
  Widget _buildHeartRateMeasureCard() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '心率测量',
              style: Get.textTheme.titleMedium,
            ),
            const SizedBox(height: 12),
            Row(
              children: [
                Expanded(
                  child: ElevatedButton.icon(
                    onPressed: controller.isLoading ? null : controller.startHeartRateMeasure,
                    icon: const Icon(Icons.play_arrow),
                    label: const Text('开始测量'),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.green,
                      foregroundColor: Colors.white,
                    ),
                  ),
                ),
                const SizedBox(width: 8),
                Expanded(
                  child: ElevatedButton.icon(
                    onPressed: controller.isLoading ? null : controller.stopHeartRateMeasure,
                    icon: const Icon(Icons.stop),
                    label: const Text('停止测量'),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.orange,
                      foregroundColor: Colors.white,
                    ),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  /// 构建电池指示器
  Widget _buildBatteryIndicator() {
    return Obx(() {
      final battery = controller.battery;
      final isCharging = controller.isCharging;
      final color = _getBatteryColor(battery, isCharging);
      
      return Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(
            _getBatteryIcon(battery, isCharging),
            color: color,
            size: 20,
          ),
          const SizedBox(width: 4),
          Text(
            isCharging ? '充电中' : '${battery}%',
            style: Get.textTheme.bodySmall?.copyWith(color: color),
          ),
        ],
      );
    });
  }

  /// 获取状态颜色
  Color _getStatusColor() {
    switch (controller.connectionState) {
      case RingConnectionState.connected:
        return Colors.green;
      case RingConnectionState.connecting:
        return Colors.orange;
      case RingConnectionState.disconnected:
        return Colors.grey;
    }
  }

  /// 获取状态图标
  IconData _getStatusIcon() {
    switch (controller.connectionState) {
      case RingConnectionState.connected:
        return Icons.bluetooth_connected;
      case RingConnectionState.connecting:
        return Icons.bluetooth_searching;
      case RingConnectionState.disconnected:
        return Icons.bluetooth_disabled;
    }
  }

  /// 获取电池颜色
  Color _getBatteryColor(int battery, bool isCharging) {
    if (isCharging) return Colors.green; // 充电中显示绿色
    if (battery < 20) return Colors.red;
    if (battery < 50) return Colors.orange;
    return Colors.green;
  }

  /// 获取电池图标
  IconData _getBatteryIcon(int battery, bool isCharging) {
    if (isCharging) return Icons.battery_charging_full; // 充电中显示充电图标
    if (battery == 0) return Icons.battery_unknown;
    if (battery < 20) return Icons.battery_0_bar;
    if (battery < 40) return Icons.battery_2_bar;
    if (battery < 60) return Icons.battery_4_bar;
    if (battery < 80) return Icons.battery_5_bar;
    return Icons.battery_full;
  }
}
